package cn.rkylin.oms.goodscost.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.export.IExport;
import cn.rkylin.oms.goodscost.dao.IGoodsCostDAO;
import cn.rkylin.oms.goodscost.service.IGoodsCostService;
import cn.rkylin.oms.goodscost.vo.GoodsCostVO;
import cn.rkylin.oms.system.project.vo.ProjectVO;

/**
 * 
 * 类名：GoodsCostController <br>
 * 作用：商品成本控制层 <br>
 * 创建时间：2018年1月16日 上午10:52:58
 *
 * @author LiPeng
 * @version
 */
@Controller
@RequestMapping("/goodsCost")
public class GoodsCostController extends ApolloController {

    private static final Log logger = LogFactory.getLog(GoodsCostController.class);

    /**
     * 商品成本服务层
     */
    @Autowired
    private IGoodsCostService goodsCostService;

    @Override
    public void afterPropertiesSet() throws Exception {
        setExportService((IExport) goodsCostService);
    }

    /**
     * getGoodsCostList:查询商品成本列表
     * 
     * @param quickSearch
     * @param start
     * @param length
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getGoodsCostList")
    public Map<String, Object> getGoodsCostList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length) throws Exception {
        logger.info("查询商品成本：/goodsCost/getGoodsCostList");

        GoodsCostVO queryParamVO = new GoodsCostVO();

        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            return getFailedMap("查询当前登录人失败");
        }
        // 获取当前登录人所属项目
        String projectId = currentUser.getCurrentProject().getPrjId();
        if (StringUtils.isBlank(projectId)) {
            return getFailedMap("查询当前登录人所属项目失败");
        }
//        String entId = null;
//        // 找前台选择的项目，对应的企业（这种做法是为了适应，用户对应到多个企业下的情况。）
//        for (ProjectVO project : currentUser.getProjectMap().values()) {
//            if (project.getPrjId().equalsIgnoreCase(projectId)) {
//                entId = project.getEntId();
//            }
//        }
//        queryParamVO.setEntId(entId);
        queryParamVO.setPrjId(projectId);

        // 快速查询
        if (quickSearch != null && StringUtils.isNotEmpty(quickSearch)) {
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                queryParamVO.setQuickSearch(quickSearch.trim());
            }
        }

        Map<String, String> replaceFieldsMap = new HashMap<String, String>();
        // 排序语句生成
        String orderStatement = getOrderString(IGoodsCostDAO.class.getName(), "pageSelectGoodsCost", replaceFieldsMap);
        if (StringUtils.isNotEmpty(orderStatement)) {
            queryParamVO.setOrderBy(orderStatement);
        }
        // 处理分页信息
        if (length == -1) {
            length = Integer.MAX_VALUE;
        }
        int page = start / length + 1;

        // 执行查询
        PageInfo<GoodsCostVO> goodsCostVOList = goodsCostService.queryGoodsCostList(page, length, queryParamVO);

        Map<String, Object> returnMap = new HashMap<>();
        if (null != goodsCostVOList) {
            returnMap = getSuccessMap("查询商品成本表单数据成功");
            returnMap.put(RECORDS_FILTERED, goodsCostVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, goodsCostVOList.getTotal());
            returnMap.put(RETURN_DATA, goodsCostVOList.getList());
        } else {
            returnMap = getFailedMap("查询商品成本表单数据失败");
        }
        logger.info("查询商品成本表单数据调用结束");
        return returnMap;
    }

    /**
     * getGoodsCost：获取商品成本
     * 
     * @param skuId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getGoodsCost")
    public Map<String, Object> getGoodsCost(@RequestParam(value = "skuId") String skuId) {
        logger.info(String.format("获取商品成本：/goodsCost/getGoodsCost/%s", skuId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            GoodsCostVO result = goodsCostService.queryGoodsCostById(skuId);
            if (null != result) {
                returnMap = getSuccessMap("系统调用完成");
                returnMap.put(RETURN_DATA, result);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    /**
     * updateGoodsCost:修改商品成本
     * 
     * @param goodsCostVO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateGoodsCost")
    @SystemControllerLog(module = "商品成本管理", operation = "修改商品成本", keyCode = "goodsId")
    public Map<String, Object> updateGoodsCost(@RequestBody GoodsCostVO goodsCostVO) {
        logger.info("修改商品成本：/goodsCost/updateGoodsCost");
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            goodsCostVO.setOperMode("手动");
            String returnMsg = goodsCostService.updateGoodsCost(goodsCostVO);
            if ("修改成功".equals(returnMsg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, returnMsg);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(RETURN_DATA, returnMsg);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap.put(JSON_RESULT, FAILED);
            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("goodsId", goodsCostVO.getGoodsId());
        return returnMap;
    }

    /**
     * showCostChangeList：查询商品成本变更列表
     * 
     * @param goodsCode
     * @param skuCode
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/showCostChangeList")
    public Map<String, Object> showCostChangeList(String goodsId, String skuId) throws Exception {
        logger.info("查询商品成本变更列表：/goodsCost/showCostChangeList");
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();

        GoodsCostVO queryParamVO = new GoodsCostVO();

        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            return getFailedMap("查询当前登录人失败");
        }
        // 获取当前登录人所属项目
        String projectId = currentUser.getCurrentProject().getPrjId();
        if (StringUtils.isBlank(projectId)) {
            return getFailedMap("查询当前登录人所属项目失败");
        }
        String entId = null;
        // 找前台选择的项目，对应的企业（这种做法是为了适应，用户对应到多个企业下的情况。）
        for (ProjectVO project : currentUser.getProjectMap().values()) {
            if (project.getPrjId().equalsIgnoreCase(projectId)) {
                entId = project.getEntId();
            }
        }
        queryParamVO.setEntId(entId);

        // 校验商品商家编码
        if (StringUtils.isBlank(goodsId)) {
            return getFailedMap("商品商家编码为空");
        } else {
            queryParamVO.setGoodsId(goodsId);
        }

        // 校验规格商家编码
        if (StringUtils.isBlank(skuId)) {
            return getFailedMap("规格商家编码为空");
        } else {
            queryParamVO.setSkuId(skuId);
        }
        //
        List<GoodsCostVO> list = goodsCostService.getCostChangeList(queryParamVO);

        // 设置返回结果内容
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(RECORDS_FILTERED, list == null ? 0 : list.size());
        returnMap.put(RECORDS_TOTAL, list.size());
        returnMap.put(RETURN_DATA, list);

        return returnMap;
    }

    private Map<String, Object> getSuccessMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

    private Map<String, Object> getFailedMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, FAILED);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

}
